package com.css.gdzj.gdzjbxgd.common.config;

import com.alibaba.fastjson.JSON;
import com.css.gdzj.gdzjbxgd.common.util.R;
import com.css.gdzj.gdzjbxgd.modules.userinfo.repository.entity.UserInfoEntity;
import com.css.gdzj.gdzjbxgd.sys.user.entity.LoginUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
/*import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;*/
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 拦截逻辑
 *
 * @author liangXG
 */
@PropertySource(value = "classpath:base.properties")
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${PERMISSION_EXCLUDE_PATH}")
    private String PERMISSION_EXCLUDE_PATH;

    ObjectMapper json = new ObjectMapper();
/*    @Autowired
    private RedisTemplate redisTemplate;*/


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession loginSession = request.getSession();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String token = request.getHeader("token");
        // 若ssion为空，或者session中用户为空，重定向到登录页面
        if (loginSession == null || (loginSession.getAttribute(token) == null)) {
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
                writer.print("{\"code\":401,\"msg\":\"请重新登录\"}");
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                if(writer!=null){
                    writer.close();
                }
            }
            return false;
        }

        UserInfoEntity user = (UserInfoEntity) loginSession.getAttribute("_USER_LOGIN_INFO_");
        String userId = user.getUserId();

        // 判断用户是否存在
        if (StringUtils.isEmpty(user) || user.equals("null")){
            return false;
        }
        System.out.println(user);
        //redisTemplate.delete("_USER_LOGIN_INFO_");
        //权限白名单，不配置权限也不会被拦截的请求放到这里
        String[] permission_exclude_path = PERMISSION_EXCLUDE_PATH.split(",");
        //当前request请求
        String reqFunc = request.getRequestURI().replaceFirst(request.getContextPath(), "");
        if (Arrays.asList(permission_exclude_path).contains(reqFunc)) {
            return true;
        }

      /*  List permission = null;
        LoginUser userInfo = (LoginUser) loginSession.getAttribute("_USER_LOGIN_INFO_");
        if(userInfo != null){
            permission = userInfo.getPermission();
        }*/

        /*if(permission != null && permission.contains(reqFunc)){
            return true;
        }else{
            return returnErrorInfo(response, "权限不足，无法查看");
        }*/
        return true;
    }

    private boolean returnErrorInfo(HttpServletResponse response, String msg) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        //权限判断
        json.writeValue(response.getOutputStream(), R.error(500, msg));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
